Python 24-Day Course - Day 21: Testing with pytest

Day 21: Testing with pytest

Installing pytest and Your First Test

pip install pytest
# calculator.py
def add(a, b):
    return a + b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
# test_calculator.py
from calculator import add, divide
import pytest

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

def test_divide():
    assert divide(10, 2) == 5.0
    assert divide(7, 2) == 3.5

def test_divide_by_zero():
    with pytest.raises(ValueError):
        divide(10, 0)

Running Tests

pytest                    # All tests
pytest test_calculator.py # Specific file
pytest -v                 # Verbose output
pytest -k "test_add"      # Filter by name

Preparing Test Data with Fixtures

import pytest

@pytest.fixture
def sample_users():
    return [
        {"name": "Alice", "age": 25},
        {"name": "Bob", "age": 30},
        {"name": "Charlie", "age": 22},
    ]

def test_user_count(sample_users):
    assert len(sample_users) == 3

def test_youngest_user(sample_users):
    youngest = min(sample_users, key=lambda u: u["age"])
    assert youngest["name"] == "Charlie"

Testing Multiple Cases with parametrize

@pytest.mark.parametrize("input_val, expected", [
    (1, False),
    (2, True),
    (3, True),
    (4, False),
    (17, True),
    (20, False),
])
def test_is_prime(input_val, expected):
    assert is_prime(input_val) == expected

Test Structure Best Practices

project/
├── src/
│   ├── calculator.py
│   └── user.py
├── tests/
│   ├── test_calculator.py
│   └── test_user.py
└── pytest.ini

Today’s Exercises

  1. Create 3 string utility functions and write tests for each.
  2. Write tests for a BankAccount class using fixtures.
  3. Use parametrize to test an email validation function with various inputs.

Was this article helpful?